package com.xu.mybatis.model;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageSerializable;
import lombok.Data;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 分页对象
 *
 * @Author: 许乾伟
 * @Date: 2024/3/21 15:48
 */
@Data
public class PageInfo<T> extends PageSerializable<T> {
    public static final PageInfo EMPTY = new PageInfo(Collections.emptyList());
    /**
     * 总记录数
     */
    protected long total;
    /**
     * 结果集
     */
    protected List<T> list;
    /**
     * 当前页
     */
    private int pageNum;
    /**
     * 每页的数量
     */
    private int pageSize;
    /**
     * 总页数
     */
    private int pages;
    /**
     * 当前页的数量
     */
    private int size;

    public PageInfo() {
    }
    /**
     * 包装Page对象
     *
     * @param list
     */
    public PageInfo(List<? extends T> list) {
        this.list = (List<T>) list;
        if(list instanceof Page){
            this.total = ((Page<?>)list).getTotal();
        } else {
            this.total = list.size();
        }
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();

            this.pages = page.getPages();
            this.size = page.size();
        } else if (list instanceof Collection) {
            this.pageNum = 1;
            this.pageSize = list.size();

            this.pages = this.pageSize > 0 ? 1 : 0;
            this.size = list.size();
        }
    }

    /**
     * 返回一个空的 Pageinfo 对象
     *
     * @return
     */
    public static <T> PageInfo<T> emptyPageInfo() {
        return EMPTY;
    }
}
